<template>
    <div>
        <el-card>
            <el-form :model="state.pageParam.param" label-width="120" ref="queryFormRef" @keyup.enter.native="loadList">
                <el-row :gutter="10">
                    <el-col :xs="3" :sm="4" :md="6" :lg="8" :xl="8">
                        <el-form-item prop="strategyName" label="策略名称">
                            <el-input v-model="state.pageParam.param.strategyName" placeholder="策略名称" clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="3" :sm="4" :md="6" :lg="8" :xl="8">
                        <el-form-item prop="strategyType" label="策略类型">
                            <DicSelect v-model="state.pageParam.param.strategyType" placeholder="请选择" dicCode="wf_strategy_type" style="width:100%"></DicSelect>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div class="btnSearchStyle">
                <el-button type="primary" class="ml7" @click="loadList">
                    <el-icon>
                        <ele-Search />
                    </el-icon>
                    查询
                </el-button>
                <el-button type="primary" class="ml10" @click="reSetForm(queryFormRef)">
                    <el-icon>
                        <ele-Refresh />
                    </el-icon>
                    重置
                </el-button>
            </div>
        </el-card>
        <el-card>
            <div class="btnStyle">
                <el-button type="success" icon="ele-Plus" @click="addOrUpdateHandle()">新增</el-button>
            </div>
            <el-table :data="state.dataList" style="width: 100%">
                <el-table-column prop="strategyName" header-align="center" align="center" label="策略名称" />
                <el-table-column prop="strategyType" header-align="center" align="center"
                    label="策略类型" :formatter="formatStatus"/>
                <el-table-column prop="strategySql" header-align="center" align="center" label="SQL" />
                <el-table-column prop="strategyParam" header-align="center" align="center" label="参数" />
                <el-table-column prop="serverName" header-align="center" align="center" label="服务名" />
                <el-table-column prop="apiUrl" header-align="center" align="center" label="服务接口" />
                <el-table-column fixed="right" header-align="center" align="center" width="150" label="操作">
                    <template #default="scope">
                        <el-button type="primary" link @click="updateHandle(scope.row)">修改</el-button>
                        <el-button type="primary" link @click="deleteHandle(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination @size-change="onHandleSizeChange" @current-change="onHandleCurrentChange" :pager-count="5"
                :page-sizes="[10, 50, 200]" v-model:current-page="state.pageParam.page" background
                v-model:page-size="state.pageParam.pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="state.total" small>
            </el-pagination>
        </el-card>
        <el-dialog :close-on-click-modal="false" :title="!state.submitForm.id ? '新增' : '修改'" ref="addOrUpdate"
            v-model="state.addOrUpdateVisible">
            <el-form :model="state.submitForm" :rules="state.submitFormRule" ref="ruleFormRef"
                @keyup.enter.native="dataFormSubmit(ruleFormRef)" label-width="120px">
                <el-form-item label="策略名称" prop="strategyName">
                    <el-input v-model="state.submitForm.strategyName" placeholder="策略名称" maxlength="255"></el-input>
                </el-form-item>
                <el-form-item label="策略类型" prop="strategyType">
                    <DicSelect v-model="state.submitForm.strategyType" placeholder="请选择" dicCode="wf_strategy_type" style="width:100%"></DicSelect>
                </el-form-item>
                <el-form-item label="本地SQL" prop="strategySql">
                    <el-input v-model="state.submitForm.strategySql" placeholder="类型是sql的情况在这配置SQL"
                        maxlength="2000"></el-input>
                </el-form-item>
                <el-form-item label="参数" prop="strategyParam">
                    <el-input v-model="state.submitForm.strategyParam" placeholder="参数" maxlength="500"></el-input>
                </el-form-item>
                <el-form-item label="服务名" prop="serverName">
                    <el-input v-model="state.submitForm.serverName" placeholder="服务调用的时候在这儿配服务名" maxlength="500"></el-input>
                </el-form-item>
                <el-form-item label="具体接口" prop="apiUrl">
                    <el-input v-model="state.submitForm.apiUrl" placeholder="服务调用时的具体接口" maxlength="500"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="state.addOrUpdateVisible = false">取消</el-button>
                    <el-button type="primary" @click="dataFormSubmit(ruleFormRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts" name="wfStrategy">
import { ElMessage, ElMessageBox, FormInstance, ElLoading } from 'element-plus'
import { workflowApi } from '/@/api/sys/workflow-api'
import { ref, reactive, onMounted, watch } from 'vue'
import { getDataDictionaryList } from '/@/utils/cacheDic'
const queryFormRef = ref<FormInstance>()
const ruleFormRef = ref<FormInstance>()
const state = reactive({
    listLoading: false,
    total: 0,
    dataList: [],
    dataListSelections: [],
    dataDictionaryList: {} as any,
    pageParam: {
        page: 1,
        pageSize: 10,
        param: {
            id: '',
            strategyName: '',
            strategyType: '',
            strategySql: '',
            strategyParam: '',
            serverName: '',
            apiUrl: '',
        }
    },
    addOrUpdateVisible: false,
    submitForm: {
        id: '',
        strategyName: '',
        strategyType: '',
        strategySql: '',
        strategyParam: '',
        serverName: '',
        apiUrl: '',
    },
    submitFormRule: {
        strategyName: [
            { required: true, message: '策略名称不能为空', trigger: 'blur' }
        ],
        strategyType: [
            { required: true, message: '策略类型不能为空', trigger: 'blur' }
        ],
        serverName:{required: true, message: '服务名不能为空', trigger: 'blur'},
        apiUrl:{required: true, message: '具体接口不能为空', trigger: 'blur'}
    },
})
const loadList = () => {
    state.listLoading = true
    workflowApi.queryWfStrategyListPage(state.pageParam).then(data => {
        if (data && data.code === 0) {
            state.dataList = data.data.records
            state.total = data.data.totalRow
        } else {
            state.dataList = []
            state.total = 0
        }
    }).catch(() => {
    }).finally(() => {
        state.listLoading = false
    })
}
watch(() => state.submitForm.strategyType, (val:string) => {
	if(val === '3') {
		state.submitFormRule.serverName.required = true
		state.submitFormRule.apiUrl.required = true
	}else{
        state.submitFormRule.serverName.required = false
		state.submitFormRule.apiUrl.required = false
	}
})

// 页面加载时
onMounted(() => {
    getDataDictionaryList(state.dataDictionaryList, ['wf_strategy_type'])
    // 列表查询
    loadList()
})

//重置
const reSetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
    state.pageParam.page = 1
    loadList()
}
// 分页改变
const onHandleSizeChange = (val: number) => {
    state.pageParam.pageSize = val;
    loadList()
}
// 分页改变
const onHandleCurrentChange = (val: number) => {
    state.pageParam.page = val;
    loadList()
}
//删除
const deleteHandle = (id: string | undefined) => {
    if (!id) {
        ElMessage.error('请选择记录！')
        return
    }
    ElMessageBox.confirm('是否确定删除所选记录', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    }).then(() => {
        workflowApi.deleteWfStrategyInfo(id).then(data => {
            if (data && data.code === 0) {
                ElMessage.success('删除成功')
                loadList()
            } else {
                ElMessage.error(data.message)
            }
        }).catch(() => {
            ElMessage.error("删除失败")
        })
    })
}
//打开新增弹窗
const addOrUpdateHandle = () => {
    state.submitForm = {
        id: '',
        strategyName: '',
        strategyType: '',
        strategySql: '',
        strategyParam: '',
        serverName: '',
        apiUrl: '',
    }
    state.addOrUpdateVisible = true
}
//打开修改弹窗
const updateHandle = (row: any | undefined) => {
    state.submitForm = {
        id: row.id,
        strategyName: row.strategyName,
        strategyType: row.strategyType,
        strategySql: row.strategySql,
        strategyParam: row.strategyParam,
        serverName: row.serverName,
        apiUrl: row.apiUrl,
    }
    state.addOrUpdateVisible = true
}
//新增修改提交
const dataFormSubmit = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid: boolean) => {
        if (valid) {
            //提交数据
            const loading = ElLoading.service({
                lock: true,
                text: '处理中',
                background: 'rgba(0, 0, 0, 0.7)',
            })
            if (!state.submitForm.id) {
                //新增
                workflowApi.saveWfStrategyInfo(state.submitForm).then(data => {
                    if (data && data.code === 0) {
                        ElMessage.success('保存成功')
                        state.addOrUpdateVisible = false
                        loadList()
                    } else {
                        ElMessage.error(data.message)
                    }
                }).catch(() => {
                    ElMessage.error('保存失败')
                }).finally(() => {
                    loading.close()
                })
            } else {
                workflowApi.updateWfStrategyInfo(state.submitForm).then(data => {
                    if (data && data.code === 0) {
                        ElMessage.success('保存成功')
                        state.addOrUpdateVisible = false
                        loadList()
                    } else {
                        ElMessage.error(data.message)
                    }
                }).catch(() => {
                    ElMessage.error('保存失败')
                }).finally(() => {
                    loading.close()
                })
            }
        }
    })
}
const formatStatus = (row: any, column: any, cellValue: string | number, index: number) => {
	
	if(Object.keys(state.dataDictionaryList).length>0){
		if (cellValue) {
			return state.dataDictionaryList['wf_strategy_type'].get(cellValue);
		}
	}
}
</script>